package common.test;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 20. 有效的括号
 */
public class _20_IsValid {

    public boolean isValid(String s) {
        if (s == null || s == "") {
            return false;
        }
        int length = s.length();
        if (length % 2 != 0) {
            return false;
        }
        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
                stack.push(s.charAt(i));
            } else {
                Character c = stack.pop();
                if (s.charAt(i) == ')' && c != '(') {
                    return false;
                }
                if (s.charAt(i) == '}' && c != '{') {
                    return false;
                }
                if (s.charAt(i) == ']' && c != '[') {
                    return false;
                }
            }
        }
        return true;
    }
}
